<template>
  <div class="create-cont"> <BasicForm @register="register" /></div>
</template>

<script setup lang="ts">
  import { onMounted, createVNode } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { createFormSchema } from './index.data';
  import { useUserStore } from '/@/store/modules/user';
  import { isArray, isString } from '/@/utils/is';
  import {
    getProxyInfoExist,
    AddProxyInfo,
    editProxyInfo,
    getTemplateList,
  } from '/@/api/flow/workItemProxy';
  import { AddWorkItemProxy } from '/@/api/flow/model/workItemProxyModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { DICT } from '/@/enums/dict';
  import { getDictTypeListApi } from '/@/api/admin/dict';
  import dayjs from 'dayjs';

  const userModule = useUserStore();
  const props = defineProps({
    setModalProps: {
      type: Function,
    },

    closeModal: {
      type: Function,
    },
    allData: {
      type: Object,
      default: () => {},
    },
  });

  const emit = defineEmits(['submit']);

  props.setModalProps!({ showOkBtn: true });

  const { createMessage } = useMessage();

  const [register, { setFieldsValue, validate, updateSchema }] = useForm({
    schemas: createFormSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 12,
    },
    labelWidth: 80,
  });

  const params: AddWorkItemProxy = {
    moduleID: 0,
    proxyType: 0,
    userID: '',
    userName: '',
    startDate: '',
    stopDate: '',
    proxyID: '',
    proxyName: '',
  };
  // 提交
  const handleSuccess = async () => {
    const values = await validate();

    const time = formatDate(values.time);

    if (isArray(time)) {
      params.startDate = `${time[0]} 00:00:00`;
      params.stopDate = `${time[1]} 23:59:59`;
    }
    params.moduleID = values.moduleID;
    params.userName = values.userName;
    params.proxyID = values.proxyUser?.[0]?.id;
    params.proxyName = values.proxyUser[0].name;
    if (props.allData.paramsObj?.isUpdate) {
      params.operationType = 0;
      await editProxyInfo(params);
      createMessage.success('操作成功');
      props.closeModal!();
      return;
    }

    const ret = await getProxyInfoExist(params);
    if (!ret) {
      await AddProxyInfo(params);
      createMessage.success('操作成功');
      props.closeModal!();
    } else {
      Modal.confirm({
        title: '确定覆盖吗？',
        icon: createVNode(ExclamationCircleOutlined),
        content: `相关内容已于 ${ret.proxyDate} 授权给 ${ret.proxyName} ，点击确认进行覆盖更新`,
        async onOk() {
          await AddProxyInfo(params);
          createMessage.success('操作成功');
          props.closeModal!();
        },
      });
    }
  };

  // 日期格式转换
  const formatDate = (date: any) => {
    if (!date || !isArray(date)) return date;
    const arr = date.map((i) => {
      if (!isString(i)) {
        return dayjs(i).format('YYYY-MM-DD');
      }
      return i;
    });
    return arr;
  };

  const initForm = () => {
    const { data, paramsObj } = props.allData;
    distinguishAuth(paramsObj.proxyType);
    if (paramsObj?.isUpdate) {
      // 编辑
      params.userID = data.userID;
      params.proxyDate = data.proxyDate;
      params.proxyStatus = data.proxyStatus.value;
      params.confirmDate = data.confirmDate;
      params.proxyType = data.proxyType;
      let startDate = '';
      let stopDate = '';
      if (data.startDate) {
        startDate = data.startDate.split(' ')[0];
      }
      if (data.startDate) {
        stopDate = data.stopDate.split(' ')[0];
      }

      setFieldsValue({
        moduleID: Number(data.moduleID),
        userName: data.userName,
        time: [startDate, stopDate],
        proxyUser: [
          {
            name: data.proxyName,
            id: data.proxyID,
          },
        ],
      });
    } else if (userModule.getUserInfo) {
      params.userID = userModule.getUserInfo.userId as string;

      setFieldsValue({
        userName: userModule.getUserInfo.name,
      });
    }
  };

  //授权类型区分
  const distinguishAuth = (type: number) => {
    params.proxyType = type;

    switch (type) {
      case 0: //公文授权
        updateSchema({
          field: 'moduleID',
          defaultValue: 0,
        });
        break;
      case 1: //类别授权
        updateSchema({
          field: 'moduleID',
          label: '授权分类',
          component: 'ApiSelect',
          dynamicDisabled: false,
          required: true,
          componentProps: {
            api: getDictTypeListApi,
            labelField: 'label',
            valueField: 'intValue',
            params: {
              type: DICT.TEMPLATE_TYPE,
            },
          },
        });
        break;
      case 2: //模板授权
        //getTemplateList
        updateSchema({
          field: 'moduleID',
          label: '授权模板',
          component: 'ApiSelect',
          dynamicDisabled: false,
          required: true,
          componentProps: {
            api: getTemplateList,
            labelField: 'templatename',
            valueField: 'templateid',
          },
        });
        break;
    }
  };

  onMounted(() => {
    initForm();
  });

  emit('submit', handleSuccess);
</script>

<style lang="less" scoped>
  .create-cont {
    width: 95%;
    margin: auto;
  }

  :deep(.ant-picker) {
    width: 100%;

    .ant-picker-input {
      input {
        text-align: center !important;
      }
    }
  }
</style>
